/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.dejax.service.impl;

import com.dejax.domain.DevopsOperation;
import com.dejax.domain.DevopsServerpath;
import com.dejax.service.dto.DevopsOperationQueryCriteria;
import com.dejax.utils.ValidationUtil;
import com.dejax.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.dejax.repository.DevopsServerpathRepository;
import com.dejax.service.DevopsServerpathService;
import com.dejax.service.dto.DevopsServerpathDto;
import com.dejax.service.dto.DevopsServerpathQueryCriteria;
import com.dejax.service.mapstruct.DevopsServerpathMapper;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.dejax.utils.PageUtil;
import com.dejax.utils.QueryHelp;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Richer
* @date 2022-01-05
**/
@Service
@RequiredArgsConstructor
public class DevopsServerpathServiceImpl implements DevopsServerpathService {

    private final DevopsServerpathRepository devopsServerpathRepository;
    private final DevopsServerpathMapper devopsServerpathMapper;
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Map<String,Object> queryAll(DevopsServerpathQueryCriteria criteria, Pageable pageable){
        criteria.setFlag(0);
        Page<DevopsServerpath> page = this.queryAllData(criteria,pageable);

        return PageUtil.toPage(page);
    }

    private Page<DevopsServerpath> queryAllData(DevopsServerpathQueryCriteria criteria, Pageable pageable){
        StringBuffer dataBuffer = new StringBuffer(
                "SELECT devops_serverpath.*,jenkinsclient.ip " +
                        "FROM devops_serverpath " +
                        "left join devops_jenkinsclient jenkinsclient on  jenkinsclient.jenkinsid =devops_serverpath.jenkinsid " +
                        "WHERE 1 = 1 ");
        StringBuffer countBuffer = new StringBuffer(
                "SELECT count(*) " +
                        "FROM devops_serverpath " +
                        "left join devops_jenkinsclient jenkinsclient on  jenkinsclient.jenkinsid =devops_serverpath.jenkinsid " +
                        "WHERE 1 = 1 ");

        StringBuffer paramBuffer = new StringBuffer();

        //功能名称
        if(criteria.getJenkinsid() != null){
            paramBuffer.append(" AND (jenkinsclient.ip = '" + criteria.getJenkinsid() + "' or  jenkinsclient.jenkinsid = '"+criteria.getJenkinsid()+"' )");
        }

        paramBuffer.append(" AND devops_serverpath.flag = 0");
        StringBuffer orderBuffer = new StringBuffer(
                "");

        String dataSql = (dataBuffer.append(paramBuffer).append(orderBuffer))
                .toString();
        String countSql = (countBuffer.append(paramBuffer)).toString();

        System.out.println("{} dataSql= " + dataSql);
        System.out.println("{} countSql= " + countSql);

        Query dataQuery = entityManager.createNativeQuery(dataSql.toString());
        Query countQuery = entityManager.createNativeQuery(countSql.toString());

        dataQuery.setFirstResult((int) pageable.getOffset());
        dataQuery.setMaxResults(pageable.getPageSize());
        dataQuery.unwrap(NativeQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        BigDecimal count = BigDecimal.valueOf(Integer.valueOf(String.valueOf(countQuery.getSingleResult())));
        Integer total = count.intValue();

        List content = total > pageable.getOffset() ? dataQuery
                .getResultList() : Collections.emptyList();

        return new PageImpl<DevopsServerpath>(content,pageable,total);
    }

    @Override
    public List<DevopsServerpathDto> queryAll(DevopsServerpathQueryCriteria criteria){
        criteria.setFlag(0);
        return devopsServerpathMapper.toDto(devopsServerpathRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DevopsServerpathDto findById(String serverpathid) {
        DevopsServerpath devopsServerpath = devopsServerpathRepository.findById(serverpathid).orElseGet(DevopsServerpath::new);
        ValidationUtil.isNull(devopsServerpath.getServerpathid(),"DevopsServerpath","serverpathid",serverpathid);
        return devopsServerpathMapper.toDto(devopsServerpath);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DevopsServerpathDto create(DevopsServerpath resources) {
        resources.setServerpathid(IdUtil.simpleUUID());
        resources.setFlag(0);
        return devopsServerpathMapper.toDto(devopsServerpathRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DevopsServerpath resources) {
        DevopsServerpath devopsServerpath = devopsServerpathRepository.findById(resources.getServerpathid()).orElseGet(DevopsServerpath::new);
        ValidationUtil.isNull( devopsServerpath.getServerpathid(),"DevopsServerpath","id",resources.getServerpathid());
        devopsServerpath.copy(resources);
        devopsServerpathRepository.save(devopsServerpath);
    }

    @Override
    public void deleteAll(String[] ids) {
        DevopsServerpath updateresource = new DevopsServerpath();
        for (String serverpathid : ids) {
            updateresource.setFlag(1);
            updateresource.setServerpathid(serverpathid);
            this.update(updateresource);
        }
    }

    @Override
    public void download(List<DevopsServerpathDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DevopsServerpathDto devopsServerpath : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("jenkins客户端", devopsServerpath.getJenkinsid());
            map.put("绝对路径", devopsServerpath.getServerpath());
            map.put("路径描述", devopsServerpath.getPathdesc());
            map.put(" flag",  devopsServerpath.getFlag());
            map.put(" notes",  devopsServerpath.getNotes());
            map.put(" reguser",  devopsServerpath.getReguser());
            map.put(" regtime",  devopsServerpath.getRegtime());
            map.put(" moduser",  devopsServerpath.getModuser());
            map.put(" modtime",  devopsServerpath.getModtime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}